package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.asms.domain.AsmsFaultAsset;
import com.ruoyi.asms.domain.AsmsFaultConfirmStage;
import com.ruoyi.asms.domain.AsmsFaultResolveStage;
import com.ruoyi.asms.domain.FaultInfoView;
import com.ruoyi.asms.domain.vo.AsmsFaultConfirmStageAppraiseVo;
import com.ruoyi.asms.service.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 故障处理结果确认信息Controller
 * 
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/AsmsFaultConfirmStage")
public class AsmsFaultConfirmStageController extends BaseController
{
    @Autowired
    private IAsmsFaultConfirmStageService asmsFaultConfirmStageService;
    @Autowired
    private IAsmsFaultResolveStageService asmsFaultResolveStageService;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private IAsmsFaultAssetService faultAssetService;
    @Autowired
    private IFaultInfoViewService faultInfoViewService;

    /**
     * 查询故障处理结果确认信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:list")
    @GetMapping("/list")
    public TableDataInfo list(AsmsFaultConfirmStage asmsFaultConfirmStage)
    {
        startPage();
        List<AsmsFaultConfirmStage> list = asmsFaultConfirmStageService.selectAsmsFaultConfirmStageList(asmsFaultConfirmStage);
        return getDataTable(list);
    }

    /**
     * 导出故障处理结果确认信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:export")
    @Log(title = "故障处理结果确认信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AsmsFaultConfirmStage asmsFaultConfirmStage) throws IOException
    {
        List<AsmsFaultConfirmStage> list = asmsFaultConfirmStageService.selectAsmsFaultConfirmStageList(asmsFaultConfirmStage);
        ExcelUtil<AsmsFaultConfirmStage> util = new ExcelUtil<AsmsFaultConfirmStage>(AsmsFaultConfirmStage.class);
        util.exportExcel(response, list, "故障处理结果确认信息数据");
    }

    /**
     * 获取故障处理结果确认信息详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:query")
    @GetMapping(value = "/{faultConfirmStageId}")
    public AjaxResult getInfo(@PathVariable("faultConfirmStageId") Long faultConfirmStageId)
    {
        return AjaxResult.success(asmsFaultConfirmStageService.selectAsmsFaultConfirmStageByFaultConfirmStageId(faultConfirmStageId));
    }

    /**
     * 新增故障处理结果确认信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:add")
    @Log(title = "故障处理结果确认信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AsmsFaultConfirmStage asmsFaultConfirmStage)
    {
        return toAjax(asmsFaultConfirmStageService.insertAsmsFaultConfirmStage(asmsFaultConfirmStage));
    }

    /**
     * 修改故障处理结果确认信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:edit")
    @Log(title = "故障处理结果确认信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AsmsFaultConfirmStage asmsFaultConfirmStage)
    {
        return toAjax(asmsFaultConfirmStageService.updateAsmsFaultConfirmStage(asmsFaultConfirmStage));
    }

    /**
     * 删除故障处理结果确认信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultConfirmStage:remove")
    @Log(title = "故障处理结果确认信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{faultConfirmStageIds}")
    public AjaxResult remove(@PathVariable Long[] faultConfirmStageIds)
    {
        return toAjax(asmsFaultConfirmStageService.deleteAsmsFaultConfirmStageByFaultConfirmStageIds(faultConfirmStageIds));
    }

    /**
     * 查询所有未评价的故障确认信息
     * @return
     */
    @GetMapping("/getNotConfirmStages")
    public R<List<AsmsFaultConfirmStage>> getNotConfirmStages() {
        List<AsmsFaultConfirmStage> list = asmsFaultConfirmStageService.list(new QueryWrapper<AsmsFaultConfirmStage>()
                .isNull(AsmsFaultConfirmStage.END_TIME));
        return R.ok(list);
    }

    /**
     * 保存故障确认信息
     * @param result 已自动打分的故障确认信息列表
     */
    @PostMapping("/saveConfirmStageInfo")
    public R<String> saveConfirmStageInfo(@RequestBody List<AsmsFaultConfirmStage> result) {
        if (result != null && result.size() > 0) {
            asmsFaultConfirmStageService.updateBatchById(result);
            List<AsmsFaultAsset> faultAssets = new ArrayList<>();
            for (AsmsFaultConfirmStage stage : result) {
                AsmsFaultAsset faultAsset = new AsmsFaultAsset();
                faultAsset.setFaultAssetId(stage.getFaultAssetId());
                faultAsset.setIsFinish(0);
                faultAssets.add(faultAsset);
            }
            faultAssetService.updateBatchById(faultAssets);
        }
        return R.ok("保存成功" + result.size() + "条");
    }

    /**
     * 发送自动评价结果的通知给维修人员
     *
     * @param faultAssetIds 系统自动评价的故障资产
     * @return
     */
    @PostMapping("/sendWxNotice")
    public R<String> sendWxNotice(@RequestBody HashSet<Long> faultAssetIds) {
        if (faultAssetIds.size() == 0) {
            return R.ok();
        }
        //构造map用于查询
        List<AsmsFaultResolveStage> resolveStages = asmsFaultResolveStageService.list(new QueryWrapper<AsmsFaultResolveStage>()
                .in(AsmsFaultResolveStage.FAULT_ASSET_ID, faultAssetIds));
        HashMap<Long, AsmsFaultResolveStage> map = new HashMap<>();
        if (resolveStages != null && resolveStages.size() != 0) {
            resolveStages.forEach(item -> map.put(item.getFaultAssetId(), item));
        }
        for (Long faultAssetId : faultAssetIds) {
            AsmsFaultResolveStage resolveStage = map.get(faultAssetId);
            AsmsFaultConfirmStageAppraiseVo vo = new AsmsFaultConfirmStageAppraiseVo();
            vo.setFaultAssetId(faultAssetId);
            vo.setAttitudeScore(5);
            vo.setEfficiencyScore(5);
            vo.setQualityScore(5);
            vo.setEvaluationContent("非常满意");
            if (resolveStage != null) {
                asyncService.sendConfirmResultToWxMaSubscribe(resolveStage, vo);
            }
        }
        return R.ok("通知成功");
    }

    /**
     * 获取最新的10条评论信息
     * @return
     */
    @GetMapping("/getLatestComments")
    public R<List<AsmsFaultConfirmStage>> getLatestComments() {
        List<AsmsFaultConfirmStage> stageList = asmsFaultConfirmStageService.list(new QueryWrapper<AsmsFaultConfirmStage>()
                .select(AsmsFaultConfirmStage.EVALUATION_CONTENT, AsmsFaultConfirmStage.END_TIME, AsmsFaultConfirmStage.FAULT_ASSET_ID)
                .isNotNull(AsmsFaultConfirmStage.EVALUATION_CONTENT).ne(AsmsFaultConfirmStage.EVALUATION_CONTENT, "")
                .orderByDesc(AsmsFaultConfirmStage.FAULT_CONFIRM_STAGE_ID).last("limit 10")
        );
        Set<Long> faultAssetIds = stageList.stream().map(AsmsFaultConfirmStage::getFaultAssetId).collect(Collectors.toSet());
        if (faultAssetIds.size() == 0) return R.ok(stageList);

        List<FaultInfoView> viewList = faultInfoViewService.list(new QueryWrapper<FaultInfoView>()
                .select(FaultInfoView.FAULT_FIND_USER_ID, FaultInfoView.FAULT_ASSET_ID)
                .in(FaultInfoView.FAULT_ASSET_ID, faultAssetIds)
        );

        Map<Long, Long> map = viewList.stream().collect(Collectors.toMap(FaultInfoView::getFaultAssetId, FaultInfoView::getFaultFindUserId));
        stageList.forEach(c -> c.setConfirmUserId(map.get(c.getFaultAssetId())));

        return R.ok(stageList);
    }
}
